﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Data.Common;
using System.Data.SqlClient;
using System.Windows;
using PersonaLibrary.PersonaliiReference;
using PersonaLibrary.Properties;
using PersonaLibrary.Search;
using PersonaLibrary.Tracer;
using PersonaLibrary.View;
using PersonaLibrary.View.CheckDuplicatesView;
using PersonaLibrary.View.Host;
using PersonaLibrary.ViewModel;
using PersonaLibrary.ViewModel.CheckDuplicatesViewModel;
using PersonaLibrary.ViewModel.CollectionViewModel;

namespace PersonaLibrary
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App
	{
		private ObservableCollection<IViewModel> _viewModelCollection;
		private View.WaitWindow _waitWindow;

		public ObservableCollection<IViewModel> ViewModelCollection
		{
			get { return _viewModelCollection; }
			set { _viewModelCollection = value; }
		}

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			_viewModelCollection = new ObservableCollection<IViewModel>();
			
			MainWindow mWindow = new MainWindow();
			mWindow.Closed += delegate { Shutdown(); };
			mWindow.ShowDialog();
		}

		private static void UpdateBase()
		{
			using (DbConnection connection = new SqlConnection(Settings.Default.PersonalizationConnectionString))
			{
				connection.Open();

				string commandText =
					"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employee' AND COLUMN_NAME = 'Email')" +
					"BEGIN ALTER TABLE Employee ADD Email nvarchar(MAX) END";

				using (DbCommand command = new SqlCommand(commandText))
				{
					command.Connection = connection;
					command.ExecuteNonQuery();
				}
			}

		}

		public void AddViewModel(IViewModel viewModel)
		{
			if(viewModel is ICollectionViewModel)
			{
				if(ViewModelCollection.All(x => x.GetType() != viewModel.GetType()))
					ViewModelCollection.Add(viewModel);
			}
			else
			{
				ViewModelCollection.Add(viewModel);
			}
		}

		public void RemoveViewModel(IViewModel viewModel)
		{
			ViewModelCollection.Remove(viewModel);
		}

		internal bool ServerAvailable { set; get; }

		internal ILogFacade Logger
		{
			get { return LoggerBuilder.GetLogger(); }
		}

		internal void ShowMessage(string message)
		{
			MessageBox.Show(message);
		}

		internal void GoToLoadView(string text)
		{
			_waitWindow = new WaitWindow();
			_waitWindow.Text = text;
			_waitWindow.Show();
		}

		internal void GoToNormal()
		{
			Action close = _waitWindow.Close;
			Dispatcher.Invoke(close, null);
		}

		private void Application_Exit(object sender, ExitEventArgs e)
		{
		}

		private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			Logger.Fault(e.Exception);
		}
	}
}
